package com.example.seckill.Util;

import com.example.seckill.VO.LoginRequest;
import com.example.seckill.common.CommonResult;
import com.example.seckill.pojo.User;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.*;

/**
 * 生成用户工具类
 */
public class UserUtil {
    private static void createUser(int count) throws Exception {
        List<User> users=new ArrayList<>();
        for(int i=0;i<count;i++){
            User user=new User();
            user.setUsername("testuser"+i);
            String password="testuser"+i;
            //加密

            String salt=SaltUtil.getSalt(8);
            String dbPass=MD5Util.inputPassToDBPass(password,salt);
            user.setPassword(dbPass);
            user.setSalt(salt);
            Random random = new Random();
            int gender = random.nextInt(2);
            user.setGender(gender);
            user.setName("测试用户"+i);
//            user.setRoles();
            users.add(user);
        }
        Connection connection=getCon();
        String sql1="insert into user(username,password,name,gender,salt) values(?,?,?,?,?)";
        String sql2="insert into user_role(user_id,role_id) values(?,?)";
        PreparedStatement pst1=connection.prepareStatement(sql1);
        PreparedStatement pst2=connection.prepareStatement(sql2);
        for(int i=0;i<users.size();i++){
            User user=users.get(i);
            pst1.setString(1,user.getUsername());
            pst1.setString(2,user.getPassword());
            pst1.setString(3,user.getName());
            pst1.setInt(4,user.getGender());
            pst1.setString(5,user.getSalt());
            pst1.addBatch();
    }
        pst1.executeBatch();
        pst1.clearParameters();
        connection.close();
        System.out.println("insert to db");
        //生成Token
//        String loginUrl="http://localhost:28080/user/login";
//        File file=new File("C:\\Users\\nuage\\Desktop\\在线选宿舍\\sec-kill\\userTestconfig.txt");
//        if(file.exists()) file.delete();
//        RandomAccessFile raf=new RandomAccessFile(file,"rw");
//        raf.seek(0);
//        for(int i=0;i<users.size();i++) {
//            User user = users.get(i);
//            URL url = new URL(loginUrl);
//            HttpURLConnection co = (HttpURLConnection) url.openConnection();
//            co.setRequestMethod("POST");
//            co.setDoOutput(true);
//            OutputStream out = co.getOutputStream();
////            String params = "username=" + user.getUsername() + "&password=" + user.getPassword();
//            Gson gson = new Gson();
//            String paramsJson = gson.toJson(user);
//            System.out.println("Json="+paramsJson);
//            out.write(paramsJson.getBytes());
//            out.flush();
//            InputStream inputStream = co.getInputStream();
//            ByteArrayOutputStream bout = new ByteArrayOutputStream();
//            byte[] buff = new byte[1024];
//            int len = 0;
//            while ((len = inputStream.read(buff)) >= 0) {
//                bout.write(buff, 0, len);
//            }
//            inputStream.close();
//            bout.close();
//            String response = new String(bout.toByteArray());
//            ObjectMapper mapper = new ObjectMapper();
//            CommonResult respBean = mapper.readValue(response, CommonResult.class);
//            String token = respBean.toString();
//            System.out.println("生成token="+token);
//            System.out.println("create userToken" + user.getUsername());
//            String row = user.getUsername() + "," + token;
//            raf.seek(row.length());
//            raf.write((row.getBytes()));
//            raf.write("\r\n".getBytes());
//            System.out.println("write to file :" + user.getUsername());
//        }
//        raf.close();
//        System.out.println("over");

        }

        private static void getToken(int cnt) throws IOException {
               // 生成Token
        String loginUrl="http://localhost:28080/user/login";
        File file=new File("C:\\Users\\nuage\\Desktop\\在线选宿舍\\sec-kill\\userTestconfig.txt");
        if(file.exists()) file.delete();
        RandomAccessFile raf=new RandomAccessFile(file,"rw");
        raf.seek(0);
        for(int i=0;i<cnt;i++) {
                LoginRequest loginRequest=new LoginRequest();
                loginRequest.setUsername("testuser"+i);
                loginRequest.setPassword(MD5Util.inputPassToFromPass("testuser"+i));
            URL url = new URL(loginUrl);

            // 打开和URL之间的连接
            HttpURLConnection co = (HttpURLConnection) url.openConnection();
            co.setRequestMethod("POST");
            co.setDoOutput(true);

            //设置header内的参数 connection.setRequestProperty("健, "值");
            co.setRequestProperty("Content-Type", "application/json");





            OutputStream out = co.getOutputStream();
//           String params = "username=" + loginRequest.getUsername() + "&password=" + loginRequest.getPassword();
//            Gson gson = new Gson();
//            String paramsJson = gson.toJson(params);
            String paramsJson=JsonUtil.object2JsonStr(loginRequest);
            System.out.println("Json="+paramsJson);
            out.write(paramsJson.getBytes());
            out.flush();
            InputStream inputStream = co.getInputStream();
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] buff = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buff)) >= 0) {
                bout.write(buff, 0, len);
            }
            inputStream.close();
            bout.close();
            String response = new String(bout.toByteArray());
            ObjectMapper mapper = new ObjectMapper();
            CommonResult respBean = mapper.readValue(response, CommonResult.class);
            Map entity = (Map)respBean.getData();
            //获取object中token的值：
            String token = entity.get("accessToken").toString();
//            String token =respBean.getData()).toString();
            System.out.println("生成token="+token);
            System.out.println("create userToken" + loginRequest.getUsername());
            String row = loginRequest.getUsername() + "," + token;
            raf.seek(raf.length());
            raf.write((row.getBytes()));
            raf.write("\r\n".getBytes());
            System.out.println("write to file :" + loginRequest.getUsername());
        }
        raf.close();
        System.out.println("over");


                }



    private static Connection getCon() throws Exception{
        String url ="jdbc:mysql://localhost:3306/seckill";
        String username ="root";
        String password ="1";
        String driver="com.mysql.cj.jdbc.Driver";
        Class.forName(driver);
        return DriverManager.getConnection(url,username,password);
    }



public static void main(String[] args) throws Exception {
//    createUser(1000);
        getToken(1000);

    }

}
